package com.fh.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.common.annotation.AutoLog;
import com.fh.common.api.vo.Result;
import com.fh.common.constant.CommonConstant;
import com.fh.common.constant.Constant;
import com.fh.common.exception.SelfDefinedException;
import com.fh.common.util.ConvertUtils;
import com.fh.common.util.PasswordUtil;
import com.fh.common.web.AbstractController;

import com.fh.modules.ucas.entity.SysUser;
import com.fh.modules.ucas.entity.SysUserDepart;
import com.fh.modules.ucas.entity.SysUserRole;
import com.fh.modules.ucas.model.DepartIdModel;
import com.fh.modules.ucas.model.SysUserDepartsVO;
import com.fh.modules.ucas.vo.SysDepartUsersVO;
import com.fh.modules.ucas.vo.SysUserRoleVO;
import com.fh.web.service.ISysUserDepartService;
import com.fh.web.service.ISysUserRoleService;
import com.fh.web.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author Qiu,Junda
 * @date 2019年4月3日
 * @description 用户表 前端控制器
 */
@RestController
@RequestMapping("/sys/user")
@Api("用户表")
public class SysUserController extends AbstractController {

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private ISysUserRoleService sysUserRoleService;

	@Autowired
	private ISysUserDepartService sysUserDepartService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ApiOperation("分页查询用户")
	@AutoLog(value = "分页查询所有用户", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result queryPageList(SysUser user, @RequestParam(name = "current", defaultValue = "1") Integer current,
								@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		user.setDelFlag(0);
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>(user);
		Page<SysUser> page = new Page<SysUser>(current, pageSize);
		// 排序逻辑 处理
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		if (ConvertUtils.isNotEmpty(column) && ConvertUtils.isNotEmpty(order)) {
			if (Constant.ORDER_ASC.equals(order)) {
				queryWrapper.orderByAsc(ConvertUtils.camelToUnderline(column));
			} else {
				queryWrapper.orderByDesc(ConvertUtils.camelToUnderline(column));
			}
		}
		IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
//	@RequiresPermissions("sys:user:create")
	@ApiOperation("新增用户")
	@AutoLog("新增用户")
	public Result<SysUser> add(@RequestBody JSONObject jsonObject) {
		Result<SysUser> result = new Result<SysUser>();
		String selectedRoles = jsonObject.getString("selectedroles");
		try {
			SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
			user.setCreateTime(new Date());
			String salt = ConvertUtils.randomGen(8);
			user.setSalt(salt);
			String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
			user.setPassword(passwordEncode);
			user.setStatus(1);
			user.setDelFlag(0);
			sysUserService.addUserWithRole(user, selectedRoles);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
//	@RequiresRoles({"admin"})
//	@RequiresPermissions("sys:user:update")
	@ApiOperation("修改用户")
	@AutoLog("修改用户")
	public Result<SysUser> eidt(@RequestBody JSONObject jsonObject) {
		Result<SysUser> result = new Result<SysUser>();
		try {
			SysUser sysUser = sysUserService.getById(jsonObject.getString("id"));
			if (sysUser == null) {
				result.error500("未找到对应实体");
			} else {
				SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
				user.setUpdateTime(new Date());
				user.setPassword(sysUser.getPassword());
				String roles = jsonObject.getString("selectedroles");
				sysUserService.editUserWithRole(user, roles);
				result.success("修改成功!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}

	@RequestMapping(value = "/editSelf", method = RequestMethod.PUT)
	@ApiOperation("修改个人信息")
	@AutoLog("修改个人用户")
	public Result editSelf(@RequestBody JSONObject jsonObject) {
		SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
		user.setUpdateTime(new Date());
		sysUserService.updateById(user);
		return Result.ok("保存成功");
	}

	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
//	@RequiresPermissions("sys:user:create")
	@ApiOperation("删除用户")
	@AutoLog("删除用户")
	public Result delete(@RequestParam(name = "id", required = true) String id) {
		sysUserService.deleteUserById(id);
		return Result.ok("删除成功");
	}

	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
//	@RequiresPermissions("sys:user:create")
	@ApiOperation("批量删除用户")
	@AutoLog("批量删除用户")
	public Result deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		String[] idList = ids.split(",");
		for (String userId : idList) {
			this.sysUserService.deleteUserById(userId);
		}
		return Result.ok("批量删除成功");
	}

	@RequestMapping(value = "/frozenBatch", method = { RequestMethod.PUT })
	@ApiOperation("解冻，冻结用户")
//	@RequiresPermissions("sys:user:frozen")
	@AutoLog("冻结和解冻用户")
	public Result frozenBatch(@RequestBody JSONObject json) {
		String ids = json.getString("ids");
		int status = json.getIntValue("status");
		String[] arr = ids.split(",");
		for (String id : arr) {
			if (ConvertUtils.isNotEmpty(id)) {
				this.sysUserService.frozenBatch(id, status);
			}
		}
		return Result.ok("操作成功");
	}

	@RequestMapping(value = "/queryCurrentUser", method = RequestMethod.GET)
	@ApiOperation("加载当前登录用户信息")
	@AutoLog(value = "加载当前登录用户信息", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result queryCurrentUser() {
		SysUser sysUser = sysUserService.getUserByName(this.getUserAccount());
		return Result.ok(sysUser);
	}

	@RequestMapping(value = "/queryById", method = RequestMethod.GET)
	@ApiOperation("根据用户id查询用户基本信息")
	@AutoLog(value = "根据用户id查询用户信息", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result<SysUser> queryById(@RequestParam(name = "id", required = true) String id) {
		Result<SysUser> result = new Result<SysUser>();
		SysUser sysUser = sysUserService.getById(id);
		if (sysUser == null) {
			result.error500("未找到对应实体");
		} else {
			result.setResult(sysUser);
			result.setSuccess(true);
		}
		return result;
	}

	@RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
	@ApiOperation("查询用户角色")
	@AutoLog(value = "查询用户角色", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
		Result<List<String>> result = new Result<>();
		List<String> list = new ArrayList<String>();
		List<SysUserRole> userRole = sysUserRoleService
				.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
		if (userRole == null || userRole.size() <= 0) {
			result.error500("未找到用户相关角色信息");
		} else {
			for (SysUserRole sysUserRole : userRole) {
				list.add(sysUserRole.getRoleId());
			}
			result.setSuccess(true);
			result.setResult(list);
		}
		return result;
	}

	/**
	 * 校验用户账号是否唯一<br>
	 * 可以校验其他 需要检验什么就传什么。。。
	 * 
	 * @return
	 */
	@RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
	@ApiOperation("验证用户账号是否存在")
	@AutoLog(value = "验证账号是否存在", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result<Boolean> checkUsername(SysUser sysUser) {
		Result<Boolean> result = new Result<>();
		SysUser dbSysUser = sysUserService.getUserByName(sysUser.getUsername());
		boolean checkResult;
		if (ConvertUtils.isEmpty(sysUser.getId())) {
			checkResult = dbSysUser == null ? true : false;
		} else {
			checkResult = sysUser.getUsername().equals(dbSysUser.getUsername()) ? true : false;
		}
		result.setResult(checkResult);
		result.setSuccess(checkResult);
		if (!checkResult) {
			result.setMessage("账号已存在！");
		}
		return result;
	}

	/**
	 * 修改密码
	 */
	@RequestMapping(value = "/changPassword", method = RequestMethod.PUT)
//	@RequiresPermissions("sys:user:updatePassword")
	@ApiOperation("修改用户密码")
	@AutoLog("修改用户密码")
	public Result<SysUser> changPassword(@RequestBody SysUser sysUserVo) {
		String username = sysUserVo.getUsername();
		String password = sysUserVo.getPassword();
		if (Constant.ADMIN_ACCOUNT.equals(username) && !Constant.ADMIN_ACCOUNT.equals(this.getUserAccount())) {
			throw new SelfDefinedException("非管理员不能修改admin账号密码");
		}
		Result<SysUser> result = new Result<SysUser>();
		SysUser sysUser = this.sysUserService
				.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
		if (sysUser == null) {
			result.error500("未找到对应实体");
		} else {
			String salt = ConvertUtils.randomGen(8);
			sysUser.setSalt(salt);
			String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
			sysUser.setPassword(passwordEncode);
			this.sysUserService.updateById(sysUser);
			result.setResult(sysUser);
			result.success("密码修改完成！");
		}
		return result;
	}

	/**
	 * 首页密码修改
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
	@AutoLog("修改本人密码")
	public Result<SysUser> changPassword(@RequestBody JSONObject json) {
		Result<SysUser> result = new Result<SysUser>();
		String username = json.getString("username");
		String oldpassword = json.getString("oldpassword");
		SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
		if (user == null) {
			result.error500("未找到用户!");
			return result;
		}
		String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
		if (!user.getPassword().equals(passwordEncode)) {
			result.error500("旧密码输入错误!");
			return result;
		}

		String password = json.getString("password");
		String confirmpassword = json.getString("confirmpassword");
		if (ConvertUtils.isEmpty(password)) {
			result.error500("新密码不存在!");
			return result;
		}

		if (!password.equals(confirmpassword)) {
			result.error500("两次输入密码不一致!");
			return result;
		}
		String newpassword = PasswordUtil.encrypt(username, password, user.getSalt());
		this.sysUserService.update(new SysUser().setPassword(newpassword),
				new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
		result.success("密码修改完成！");
		return result;
	}

	/**
	 * 查询指定用户和部门关联的数据
	 *
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
	@AutoLog(value = "查询指定用户和部门关联的数据", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result<List<DepartIdModel>> getUserDepartsList(
			@RequestParam(name = "userId", required = true) String userId) {
		Result<List<DepartIdModel>> result = new Result<>();
		try {
			List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
			if (depIdModelList != null && depIdModelList.size() > 0) {
				result.setSuccess(true);
				result.setMessage("查找成功");
				result.setResult(depIdModelList);
			} else {
				result.setSuccess(false);
				result.setMessage("查找失败");
			}
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setSuccess(false);
			result.setMessage("查找过程中出现了异常: " + e.getMessage());
			return result;
		}

	}

	/**
	 * 给指定用户添加对应的部门
	 *
	 * @param sysUserDepartsVO
	 * @return
	 */
	@RequestMapping(value = "/addUDepartIds", method = RequestMethod.POST)
	@AutoLog("给指定用户添加对应部门")
	public Result<String> addSysUseWithrDepart(@RequestBody SysUserDepartsVO sysUserDepartsVO) {
		boolean ok = this.sysUserDepartService.addSysUseWithrDepart(sysUserDepartsVO);
		Result<String> result = new Result<String>();
		try {
			if (ok) {
				result.setMessage("添加成功!");
				result.setSuccess(true);
			} else {
				throw new Exception("添加失败!");
			}
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setSuccess(true);
			result.setMessage("添加数据的过程中出现市场了: " + e.getMessage());
			return result;
		}

	}

	/**
	 * 根据用户id编辑对应的部门信息
	 *
	 * @param sysUserDepartsVO
	 * @return
	 */
	@RequestMapping(value = "/editUDepartIds", method = RequestMethod.PUT)
	@AutoLog(value = "修改用户部门信息", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result<String> editSysUserWithDepart(@RequestBody SysUserDepartsVO sysUserDepartsVO) {
		Result<String> result = new Result<String>();
		boolean ok = sysUserDepartService.editSysUserWithDepart(sysUserDepartsVO);
		if (ok) {
			result.setMessage("更新成功!");
			result.setSuccess(true);
			return result;
		}
		result.setMessage("更新失败!");
		result.setSuccess(false);
		return result;
	}

	/**
	 * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
	public Result<String> generateUserId() {
		Result<String> result = new Result<>();

		String userId = UUID.randomUUID().toString().replace("-", "");
		result.setSuccess(true);
		result.setResult(userId);
		return result;
	}

	/**
	 * 根据部门id查询用户信息
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/queryUserByDepId", method = RequestMethod.GET)
	@AutoLog(value = "根据部门查询用户", logType = CommonConstant.LOG_TYPE_QUERY)
	public Result<List<SysUser>> queryUserByDepId(@RequestParam(name = "id", required = true) String id) {
		Result<List<SysUser>> result = new Result<>();
		List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
		try {
			result.setSuccess(true);
			result.setResult(userList);
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setSuccess(false);
			return result;
		}
	}

	/**
	 * 给指定角色添加用户
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/addSysUserRole", method = RequestMethod.POST)
	@AutoLog("给指定角色添加用户")
	public Result<String> addSysUserRole(@RequestBody SysUserRoleVO sysUserRoleVO) {
		Result<String> result = new Result<String>();
		try {
			String sysRoleId = sysUserRoleVO.getRoleId();
			for (String sysUserId : sysUserRoleVO.getUserIdList()) {
				SysUserRole sysUserRole = new SysUserRole(sysUserId, sysRoleId);
				QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
				queryWrapper.eq("role_id", sysRoleId).eq("user_id", sysUserId);
				SysUserRole one = sysUserRoleService.getOne(queryWrapper);
				if (one == null) {
					sysUserRoleService.save(sysUserRole);
				}

			}

			result.setMessage("添加成功!");
			result.setSuccess(true);
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setSuccess(false);
			result.setMessage("出错了: " + e.getMessage());
			return result;
		}
	}

	/**
	 * 删除指定角色的用户关系
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
	@AutoLog("删除用户角色关系")
	public Result<SysUserRole> deleteUserRole(@RequestParam(name = "roleId") String roleId,
			@RequestParam(name = "userId", required = true) String userId) {
		Result<SysUserRole> result = new Result<SysUserRole>();
		try {
			QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
			queryWrapper.eq("role_id", roleId).eq("user_id", userId);
			sysUserRoleService.remove(queryWrapper);
			result.success("删除成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("删除失败！");
		}
		return result;
	}

	/**
	 * 批量删除指定角色的用户关系
	 *
	 * @param
	 * @return
	 */
	@AutoLog("批量删除角色用户关系")
	@RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.DELETE)
	public Result<SysUserRole> deleteUserRoleBatch(@RequestParam(name = "roleId") String roleId,
			@RequestParam(name = "userIds", required = true) String userIds) {
		Result<SysUserRole> result = new Result<SysUserRole>();
		try {
			QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
			queryWrapper.eq("role_id", roleId).in("user_id", Arrays.asList(userIds.split(",")));
			sysUserRoleService.remove(queryWrapper);
			result.success("删除成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("删除失败！");
		}
		return result;
	}

	/**
	 * 部门用户列表
	 */
	@AutoLog(value = "查询部门用户列表", logType = CommonConstant.LOG_TYPE_QUERY)
	@RequestMapping(value = "/departUserList", method = RequestMethod.GET)
	public Result<IPage<SysUser>> departUserList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
		Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
		String depId = req.getParameter("depId");
		String username = req.getParameter("username");
		IPage<SysUser> pageList = sysUserService.getUserByDepId(page, depId, username);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	/**
	 * 给指定部门添加对应的用户
	 */
	@AutoLog("部门添加用户")
	@RequestMapping(value = "/editSysDepartWithUser", method = RequestMethod.POST)
	public Result<String> editSysDepartWithUser(@RequestBody SysDepartUsersVO sysDepartUsersVO) {
		Result<String> result = new Result<String>();
		try {
			String sysDepId = sysDepartUsersVO.getDepId();
			for (String sysUserId : sysDepartUsersVO.getUserIdList()) {
				SysUserDepart sysUserDepart = new SysUserDepart(sysUserId, sysDepId);
				QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
				queryWrapper.eq("dept_id", sysDepId).eq("user_id", sysUserId);
				SysUserDepart one = sysUserDepartService.getOne(queryWrapper);
				if (one == null) {
					sysUserDepartService.save(sysUserDepart);
				}
			}

			result.setMessage("添加成功!");
			result.setSuccess(true);
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setSuccess(false);
			result.setMessage("出错了: " + e.getMessage());
			return result;
		}
	}

	/**
	 * 删除指定机构的用户关系
	 */
	@AutoLog("删除部门用户关系")
	@RequestMapping(value = "/deleteUserInDepart", method = RequestMethod.DELETE)
	public Result<SysUserDepart> deleteUserInDepart(@RequestParam(name = "depId") String depId,
			@RequestParam(name = "userId", required = true) String userId) {
		Result<SysUserDepart> result = new Result<SysUserDepart>();
		try {
			QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
			queryWrapper.eq("dept_id", depId).eq("user_id", userId);
			sysUserDepartService.remove(queryWrapper);
			result.success("删除成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("删除失败！");
		}
		return result;
	}

	/**
	 * 批量删除指定机构的用户关系
	 */
	@AutoLog("批量删除部门用户关系")
	@RequestMapping(value = "/deleteUserInDepartBatch", method = RequestMethod.DELETE)
	public Result<SysUserDepart> deleteUserInDepartBatch(@RequestParam(name = "depId") String depId,
			@RequestParam(name = "userIds", required = true) String userIds) {
		Result<SysUserDepart> result = new Result<SysUserDepart>();
		try {
			QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
			queryWrapper.eq("dept_id", depId).in("user_id", Arrays.asList(userIds.split(",")));
			sysUserDepartService.remove(queryWrapper);
			result.success("删除成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("删除失败！");
		}
		return result;
	}

}
